import shutil
import numpy as np
from utils import open_txt, write2txt, isMatch
import re
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.font_manager import *  # 如果想在图上显示中文，需导入这个包


PEOPLE = {
    'xxx'    :'用户名',
}


# QQ
class QQData():
    def __init__(self, data_path, people_name, refresh=True):
        self.data_path = data_path
        self.people_name = people_name

        self.content = []
        self.chat_time = [] # 聊天时间
        self.send_num = 0 # 对方发送的信息数

        self.outputs_path = r"outputs\{}".format(self.people_name)
        if refresh and os.path.exists(self.outputs_path):
            shutil.rmtree(self.outputs_path)
        os.makedirs(self.outputs_path, exist_ok=True)

        self.getData()
        self.hour_set = [self.to_hour(i) for i in self.chat_time]


    def getData(self):
        lines = open_txt(self.data_path, True)

        for line in lines: # 对于每条聊天记录
            # 如果不是发送时间和发送内容，就跳过
            if (line == '' or line == '='*64):
                continue
            strs = [r'消息.*']
            if isMatch(strs, line):
                continue

            # 日期文本, xxxx-xx-xx xxxxxxx
            if re.match(r'[0-9]{4}-[0-9]{2}-[0-9]{2}.*', line):
                self.chat_time.append(line.split(' ')[1])
                if line.split(' ')[2]==PEOPLE[self.people_name]:
                    self.send_num += 1
                continue

            # 内容文本
            self.content.append(line)

    # 仅保存小时格式的时间
    def to_hour(self, t):
        return int(t.split(':')[0])

    def saveChat(self):
        write2txt('\n'.join(self.content), os.path.join(self.outputs_path, 'chat_all.txt'))

    def getChatPath(self):
        return os.path.join(self.outputs_path, 'chat_all.txt')

    def timeSta(self):
        time_slice = [0, 0, 0, 0, 0, 0]
        labels = ['凌晨2点至6点', '6点至10点', '10点至14点',
                  '14点至18点', '18点至22点', '22点至次日凌晨2点']

        for i in range(len(self.hour_set)):
            if self.hour_set[i] >= 2 and self.hour_set[i] < 6:
                time_slice[0] += 1
            elif self.hour_set[i] >= 6 and self.hour_set[i] < 10:
                time_slice[1] += 1
            elif self.hour_set[i] >= 10 and self.hour_set[i] < 14:
                time_slice[2] += 1
            elif self.hour_set[i] >= 14 and self.hour_set[i] < 18:
                time_slice[3] += 1
            elif self.hour_set[i] >= 18 and self.hour_set[i] < 22:
                time_slice[4] += 1
            else:
                time_slice[5] += 1

        time_distribution = {
            labels[0]: time_slice[0],
            labels[1]: time_slice[1],
            labels[2]: time_slice[2],
            labels[3]: time_slice[3],
            labels[4]: time_slice[4],
            labels[5]: time_slice[5]
        }

        print("共计聊天记录： {}条".format(len(self.chat_time)))
        print(time_distribution)
        write2txt("共计聊天记录： {}条".format(len(self.chat_time)), os.path.join(self.outputs_path, 'out.txt'))
        write2txt(time_distribution, os.path.join(self.outputs_path, 'out.txt'))

    # 聊天时间统计图画图
    def draw(self, show=False):
        myfont = FontProperties(fname=r'C:\Windows\Fonts\MSYH.TTC', size=22)  # 标题字体样式
        myfont2 = FontProperties(fname=r'C:\Windows\Fonts\MSYH.TTC', size=18)  # 横纵坐标字体样式
        sns.set_style('darkgrid')  # 设置图片为深色背景且有网格线
        sns.distplot(self.hour_set, 24, color='lightcoral')
        plt.xticks(np.arange(0, 25, 1.0), fontsize=15)
        plt.yticks(fontsize=15)
        plt.title('聊天时间分布', fontproperties=myfont)
        plt.xlabel('时间段', fontproperties=myfont2)
        plt.ylabel('聊天时间分布', fontproperties=myfont2)
        fig = plt.gcf()
        fig.set_size_inches(20, 10)
        fig.savefig(os.path.join(self.outputs_path, 'chat_time.png'), dpi=100)
        if show:
            plt.show()

    # 关键字，字符统计
    def countChar(self):
        pattern1 = '.*?(收到).*?'
        pattern2 = '.*?(好的).*?'
        pattern3 = '.*?(老师).*?'
        pattern4 = '.*?(论文).*?'
        pattern5 = '.*?(可以).*?'
        pattern_set = [pattern1, pattern2, pattern3, pattern4, pattern5]
        statistic = [0, 0, 0, 0, 0]

        for i in range(len(self.content)):
            for j in range(len(pattern_set)):
                length = len(re.findall(pattern_set[j], str(self.content[i])))
                statistic[j] += length

        result = {
            '收到': statistic[0],
            '好的': statistic[1],
            '老师': statistic[2],
            '论文': statistic[3],
            '可以': statistic[4]
        }

        print(result)
        write2txt(result, os.path.join(self.outputs_path, 'out.txt'))

    # 双方各自发送的信息条数统计
    def countPeoNum(self):
        p = "自己发送的信息条数：{}，对方发送的信息条数：{}".format(len(self.chat_time)-self.send_num, self.send_num)
        print(p)
        write2txt(p, os.path.join(self.outputs_path, 'out.txt'))

